﻿using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Enum;
using Matrix.MaKaYunShang.Model.Wechat;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    [Authorization]
    public class VerifyController : BaseController
    {
        [PermissionFilter]
        public ActionResult Index()
        {
            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                return View();
            }

            var wechatInfo = GetWeChatInfoByMcId(projectInfo);
            if (wechatInfo != null && wechatInfo.Id > 0)
            {
                var nonstr = JsTicket.getnonstr(16);
                var resultTicket = MatrixCloudCenterInterFuncBllobj.GetWechatJsApiTicket(projectInfo.PjMcId,
                    projectInfo.PjSecret);
                if (!resultTicket.Status)
                {
                    return View();
                }

                var timestamp = (DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
                ViewBag.jsapi_ticket = resultTicket.Data;
                ViewBag.AppId = wechatInfo.AppId;
                ViewBag.nonstr = nonstr;
                ViewBag.timestamp = timestamp;
            }
            else
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            return View();
        }

        public ActionResult QrCode()
        {
            var timestamp = (DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
            string nonstr = JsTicket.getnonstr(16);
            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            var wechatInfo = GetWeChatInfoByMcId(projectInfo);
            if (wechatInfo == null || wechatInfo.Id == 0)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            var resultTicket = MatrixCloudCenterInterFuncBllobj.GetWechatJsApiTicket(projectInfo.PjMcId,projectInfo.PjSecret);
            if (!resultTicket.Status)
            {
                return new HttpStatusCodeResult(HttpStatusCode.InternalServerError);
            }
            wechatInfo.JsapiTicket = resultTicket.Data;
            wechatInfo.AppId = wechatInfo.AppId;
            wechatInfo.Nonstr = nonstr;
            wechatInfo.Timestamp = timestamp;
            return View(wechatInfo);
        }
        /// <summary>
        /// 核销方法
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult AjaxVerify(string code)
        {
            var result = new Result { Message = "核销成功", Status = true };
            var mcAccounts = McAccountsBLL.Instance.GetModel(CurrentUser.AccountId);
            if (mcAccounts.Disabled)
            {
                result.Message = "你的账号没有核销权限!";
                return Json(result);
            }

            var userCard = UserCardBLL.Instance.GetModelByCardCode(code);
            if (userCard == null)
            {
                result.Message = "卡劵不存在!";
                return Json(result);
            }
            if ((userCard.EndTime < DateTime.Now || userCard.CardStatus != 0))
            {
                Logger.Error("VerifyController.cs | Verify | 卡劵已过期,或 不等于未使用状态 ");
                result.Message = "卡劵过期或已核销!";
                return Json(result);
            }
            if (CurrentUser.ShopId != userCard.ShopId &&userCard.ShopId != CurrentUser.ParentShopId)
            {
                result.Message = "此优惠券不属于您的店铺，无法核销！";
                return Json(result);
            }
            if (userCard.ShopId == CurrentUser.ParentShopId)
            {
                if (!userCard.UsableShopIds.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Contains(CurrentUser.ShopId.ToString()))
                {
                    if (CurrentUser.ShopId != userCard.ShopId || userCard.ShopId != CurrentUser.ParentShopId)
                    {
                        result.Message = "此优惠券不属于您的店铺，无法核销！";
                        return Json(result);
                    }
                }
            }
            if (userCard.ShopId == CurrentUser.ShopId)
            {
                var cardRuleBase = CardRuleBaseBLL.Instance.GetModelByShopId(CurrentUser.ShopId);
                if (cardRuleBase != null)
                {
                    var cardRuleDetailList = CardRuleDetailBLL.Instance.GetModelByRuleBaseId(cardRuleBase.Id);
                    var cardRuleDetail = cardRuleDetailList.FirstOrDefault(s => s.CloudCardId == userCard.CloudCardId);
                    if (cardRuleDetail == null)
                    {
                        Logger.Error("VerifyController.cs | Verify | 卡劵已过期,或 不等于未使用状态 ");
                        result.Message = "卡劵过期或已核销!";
                        return Json(result);
                    }
                }
            }

            var shopSubsidiaryInfo = ShopSubsidiaryInfoBLL.Instance.GetModelByShopId(mcAccounts.ShopId);
            var sysConfig = SysConfigBLL.Instance.GetModelList().FirstOrDefault();
            if (sysConfig != null)
            {
                if (shopSubsidiaryInfo == null || shopSubsidiaryInfo.AccountMoney < sysConfig.ShopShareAmount + sysConfig.PlatformShareAmount)
                {
                    Logger.Error("VerifyController | AjaxVerify | 商家余额不足,卡卷核销失败 ");
                    result.Message = "余额不足,卡卷核销失败!";
                    return Json(result);
                }
                if (userCard.SendCardShopId > 0) //如果有其他商家id
                {
                    var otherShopSubsidiaryInfo = ShopSubsidiaryInfoBLL.Instance.GetModelByShopId(userCard.SendCardShopId);
                    if (otherShopSubsidiaryInfo != null)
                    {
                        shopSubsidiaryInfo.AccountMoney = shopSubsidiaryInfo.AccountMoney - sysConfig.ShopShareAmount;//商家账号减去扣除金额
                        shopSubsidiaryInfo.ShopTotalPayMoney = shopSubsidiaryInfo.ShopTotalPayMoney +
                                                               sysConfig.ShopShareAmount;
                        shopSubsidiaryInfo.TotalPayMoney = shopSubsidiaryInfo.TotalPayMoney + sysConfig.ShopShareAmount;
                        //分润金额
                        otherShopSubsidiaryInfo.AccountMoney = otherShopSubsidiaryInfo.AccountMoney +
                                                               sysConfig.ShopShareAmount;
                        otherShopSubsidiaryInfo.UpdateTime = DateTime.Now;
                        if (ShopSubsidiaryInfoBLL.Instance.Update(otherShopSubsidiaryInfo))
                        {
                            //其他商家
                            AddShopMoneyChangeRecord(otherShopSubsidiaryInfo.AccountMoney + sysConfig.ShopShareAmount,
                                otherShopSubsidiaryInfo.AccountMoney, sysConfig.ShopShareAmount,
                                CloudCardEnum.MerchantMoneyChangeSource.商户提取商户佣金, otherShopSubsidiaryInfo.ShopId,
                                mcAccounts.Id, mcAccounts.MxProjectInfoId, mcAccounts.ShopId);
                            //商家
                            AddShopMoneyChangeRecord(shopSubsidiaryInfo.AccountMoney,
                                shopSubsidiaryInfo.AccountMoney - sysConfig.ShopShareAmount,
                                0 - sysConfig.ShopShareAmount, CloudCardEnum.MerchantMoneyChangeSource.商户支出商户佣金,
                                shopSubsidiaryInfo.ShopId, mcAccounts.Id, mcAccounts.MxProjectInfoId, 0);
                        }
                    }
                }
                shopSubsidiaryInfo.AccountMoney = shopSubsidiaryInfo.AccountMoney - sysConfig.PlatformShareAmount;
                shopSubsidiaryInfo.PlatformTotalPayMoney = shopSubsidiaryInfo.PlatformTotalPayMoney +
                                                       sysConfig.PlatformShareAmount;
                shopSubsidiaryInfo.TotalPayMoney = shopSubsidiaryInfo.TotalPayMoney + sysConfig.PlatformShareAmount;
                shopSubsidiaryInfo.UpdateTime = DateTime.Now;
                ShopSubsidiaryInfoBLL.Instance.Update(shopSubsidiaryInfo);
                AddShopMoneyChangeRecord(shopSubsidiaryInfo.AccountMoney - sysConfig.PlatformShareAmount,
                    shopSubsidiaryInfo.AccountMoney, 0 - sysConfig.PlatformShareAmount,
                    CloudCardEnum.MerchantMoneyChangeSource.平台扣除商户佣金, mcAccounts.ShopId, mcAccounts.Id,
                    mcAccounts.MxProjectInfoId, null);
            }
            userCard.CardStatus = (int)CloudCardEnum.UserCardStatus.已核销;
            userCard.UpdateOperat = (int)CloudCardEnum.UserCardUpdateOperat.核销;
            userCard.UpdateTime = DateTime.Now;
            userCard.VerifyIp = IpHelper.IPAddress;
            userCard.VerifyMerchantUserId = CurrentUser.AccountId;
            userCard.VerifyTime = DateTime.Now;
            userCard.VerifyShopId = CurrentUser.ShopId;
            if (!UserCardBLL.Instance.Update(userCard))
            {
                result.Message = "核销失败!";
            }
            result.Message = userCard.CardName + ":核销成功!";
            return Json(result);
        }

        /// <summary>
        /// 添加商家资金变动记录
        /// </summary>
        /// <param name="afterMoney">变动后金额</param>
        /// <param name="beforeMoney">变动前金额</param>
        /// <param name="changeMoney">变动金额</param>
        /// <param name="merchantMoneyChangeSource">变动来源(0充值1红包发放2商品货款3商品退款)</param>
        /// <param name="shopId">shopId</param>
        /// <param name="operaUserId">操作人员id</param>
        /// <param name="mxProjectInfoId">mxProjectInfoId</param>
        /// <param name="shareShopId">分享店铺id</param>
        public void AddShopMoneyChangeRecord(decimal afterMoney, decimal beforeMoney, decimal changeMoney,
            CloudCardEnum.MerchantMoneyChangeSource merchantMoneyChangeSource, int shopId, int operaUserId,
            int mxProjectInfoId, int? shareShopId)
        {
            var model = new ShopMoneyChangeRecord
            {
                AddTime = DateTime.Now,
                AfterMoney = afterMoney,
                BeforeMoney = beforeMoney,
                ChangeMoney = changeMoney,
                ChangeSerialNumber = null,
                ChangeSource = (int)merchantMoneyChangeSource,
                ShopId = shopId,
                OperaUserId = operaUserId,
                OperaSource = (int)CloudCardEnum.MerchantMoneyOperaSource.平台,
                OperaResult = (int)CommonEnum.OperaResult.操作成功,
                MxProjectInfoId = mxProjectInfoId,
                ShareShopId = shareShopId
            };
            if (ShopMoneyChangeRecordBLL.Instance.Add(model) < 1)
            {
                Logger.Error("VerifyController | AddShopMoneyChangeRecord | 商家资金变动记录写入错误:ShopId= " + shopId + ",AfterMoney:+" + afterMoney + ",BeforeMoney=" + beforeMoney + ",ChangeMoney=" + changeMoney + ",OperaUserId=" + operaUserId);
            }
        }

        public ActionResult Listing()
        {


            return View();
        }
    }
}
